﻿/***************************************************/
/************ OPENWEB CHAT  ************************/
/***************************************************/
(function ($)
{
    var _userName;
    var _userID;
    $.fn.OpenWebChat = function (userID)
    {

        if (userID != null)
        {
            setTimeout('GetMessage("' + userID + '")', 0);
            setTimeout('refreshContactList("' + userID + '")', 3000);
           // setTimeout('refreshChatBoxPosition()', 1000);   
        };


        /***************************************************/
        /************ OPENWEB CHAT HTML ********************/
        /***************************************************/
        var html = "";


        html = html + "<div id='ChatWrapper'>";
        html = html + "<div id='ChatWrapperIn'>";

        html = html + "<div id='chatBar' userID='" + userID + "'>";
        html = html + "<div class='btnChat' onClick='ToggleDiv(\".contactList\");refreshContactList(\"" + userID + "\");'><img src='/App_Themes/OpenWeb/OwImages/vi-VN/UsersChat.png'/><span> CHAT </span></div>";

        html = html + "</div>";

        /*Hiển thị danh sách liên hệ */
        html = html + "<div class='contactList'>";
        html = html + "<div class='titleContactList'>Danh sách liên hệ</div>";
        html = html + "<div class='contentContactList'></div>";
        html = html + "";
        html = html + "";
        html = html + "</div>";

        this.append(html);
        //Lấy thông tin từ cookie nếu có.
        loadcookieData();
    };

})(jQuery);


/***********************************************/
/***************   FUNCIONES      **************/
/***********************************************/



function ToggleDiv(div)
{
    $(div).toggle();
}



function toogleChatBox(idChatBox)
{
    if ($("#chatBox" + idChatBox).is(":visible"))
    {
        $("#chatBox" + idChatBox).hide();
        $("#ChatTabBar" + idChatBox).css("background-color", "#EBEEF4").css("box-shadow", "0 1px 1px rgba(0, 0, 0, 0.3)");
        //Save cookie
        $.cookie("maximizedChatBox", null);
    }
    else
    {
        //Ẩn hết cửa sổ chat khác
        $.each($(".chatBox"), function ()
        {
            $(this).hide();
        });
        //Cho Tab màu xám
        $.each($(".ChatTabBar"), function ()
        {
            $(this).css("background-color", "#EBEEF4");
        });

        $("#chatBox" + idChatBox).show();
        $("#ChatTabBar" + idChatBox).css("background-color", "white");
        //Save cookie 
        $.cookie("maximizedChatBox", idChatBox);
    }
}

function loadcookieData()
{
    if ($.cookie("activeChats") != null)
    {
        var activeChats = $.cookie('activeChats').split("*");
        var maximizedChat = $.cookie("maximizedChatBox");
        var blinkChats = null;
        if ($.cookie('blinkChat') != null)
            blinkChats = $.cookie('blinkChat').split("*");

        var i = 0;
        for (i = 0; i < activeChats.length; i++)
        {
            if (activeChats[i] != "")
            {
                $.ajax({
                    type: "POST",
                    url: "MessageServices.asmx/GetUserName",
                    data: '{"userID":"' + activeChats[i] + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msj)
                    {
                        //alert('a');
                        if (msj.d != "error")
                        {
                            createChatWindow(activeChats[i], msj.d);
                            $("#chatBox" + activeChats[i] + " .contentDiv").append($.cookie("chat" + activeChats[i]));
                            $("#chatBox" + activeChats[i] + " .contentDiv").scrollTop($("#chatBox" + activeChats[i] + " .contentDiv").attr("scrollHeight") - $("#chatBox" + activeChats[i] + " .contentDiv").height());
                        }
                    },
                    error: function ()
                    {
                        action = 1;
                    },
                    async: false
                });

            }
        }
        //Ẩn các cửa sổ chat
        $.each($(".chatBox"), function ()
        {
            $(this).hide();
        });
        $(".ChatTabBar").css("background-color", "#EBEEF4");
        if (maximizedChat != null)
        {
            $("#chatBox" + maximizedChat).show();
            $("#ChatTabBar" + maximizedChat).css("background-color", "white");
            $.cookie("maximizedChatBox", maximizedChat);
        }
        else
            $.cookie("maximizedChatBox", null);

        if (blinkChats != null)
        {
            i = 0;
            for (i = 0; i < blinkChats.length; i++)
            {
                blinkChatTabBar(blinkChats[i]);
            }
        }
    }
}

function quitarTextoParpad(ChatTabID)
{
    $("#ChatTabBar" + ChatTabID).css("color", "black");
    //Lấy các cửa sổ chat dạng blink từ cookie.
    if ($.cookie("blinkChat") != null)
    {
        idsConvers = $.cookie('blinkChat').split("*");
        var i = 0;
        var idConversNew = "";
        for (i = 0; i < idsConvers.length; i++)
        {
            if (idsConvers[i] != ChatTabID)
            {
                if (idConversNew == "")
                    idConversNew = idsConvers[i];
                else
                    idConversNew = idConversNew + "*" + idsConvers[i];
            }
        }
        $.cookie("blinkChat", idConversNew);
    }
}

function blinkChatTabBar(ChatTabID)
{
    $("#ChatTabBar" + ChatTabID).css("color", "red").fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
    //Lưu cửa sổ đang trò chuyện vào cookie   
    if ($.cookie("blinkChat") != null)
    {
        //Kiểm tra xem đã có trong DB hay chưa, nếu chưa thì không add.
        idsConvers = $.cookie('blinkChat').split("*");
        var i = 0;
        var exist = false;
        for (i = 0; i < idsConvers.length; i++)
        {
            if (idsConvers[i] == ChatTabID)
            {
                exist = true;
            }
        }
        if (!exist)
            if ($.cookie("blinkChat") != "")
                $.cookie("blinkChat", $.cookie("blinkChat") + "*" + ChatTabID);
            else
                $.cookie("blinkChat", ChatTabID);
    }
    else
        $.cookie("blinkChat", ChatTabID);
}

function closeChatBox(idChatBox)
{
    $("#chatBox" + idChatBox).remove();
    $("#ChatTabBar" + idChatBox).remove();
    refreshChatBoxPosition();

    //Xóa tab đóng khỏi cookie
    if ($.cookie("activeChats") != null)
    {
        idsConvers = $.cookie('activeChats').split("*");
        var i = 0;
        var idConversNew = "";
        for (i = 0; i < idsConvers.length; i++)
        {
            if (idsConvers[i] != idChatBox)
            {
                if (idConversNew == "")
                    idConversNew = idsConvers[i];
                else
                    idConversNew = idConversNew + "*" + idsConvers[i];
            }
        }
        $.cookie("activeChats", idConversNew);
    }
    //Xóa chat
    $.cookie("chat" + idChatBox, null);
}



function refreshChatBoxPosition()
{
    $.each($(".ChatTabBar"), function ()
    {
        id = $(this).attr('id');
        res = id.substring(10, id.length);
        var offset = $("#ChatTabBar" + res).offset().left - 85;
        if (offset != $("#chatBox" + res).offset().left)
            $("#chatBox" + res).offset({ left: offset });
    });
}
$(function ()
{
    $('#filterUserTxt').live('keyup', function (event)
    {
        var filterText = $.trim($(this).val().toLowerCase());
        if (filterText.length == 0)
        {
            $(this).next().find('td.chatUserNameTd').each(function ()
            {
                $(this).parent().show();
            });
        }
        else
        {
            $(this).next().find('td.chatUserNameTd').each(function ()
            {
                if ($(this).text().toLowerCase().indexOf(filterText) == 0)
                {
                    $(this).parent().show();
                }
                else
                {
                    $(this).parent().hide();
                }
            });
        }
    });
});
function refreshContactList(userID)
{
    //Option action
    //0 - html
    //1 - error
    var action = 0;
    var html = "";
    var json;
    $.ajax({
        type: "POST",
        url: "/Views/Shared/InstantMessage/MessageServices.asmx/GetContactList",
        data: '{"userID":"' + userID + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msj)
        {
            if (msj.d != "error")
            {
                action = 0;
                eval('var z=' + msj.d);
                json = z;
            }
            else
                action = 1;

        },
        error: function ()
        {
            action = 1;
            //alert('Error');
        },
        async: false
    });

    if (action == 0)
    {

        if (json.ToTalUserCount == 0)
        {
            html = html + "<table><tr><td>Không có ai trực tuyến!</td></tr></table>";
            $(".btnChat span").html("User (0)");
        }
        else
        {
            var i = 0;
            //            
            $.each($(".chatBox span"), function ()
            {
                $(this).html(""); //demo demo demo                
            });
            html += "<input type='text' class='filterUserInContact' id='filterUserTxt'/>";
            html = html + "<table id='tblContactLst'>";
            var totalUser = 0;
            while (i < json.GroupCount)
            {
                html += "<tr><td colspan=\"2\">" + json.ListContactGroupDetail[i].GroupName + "</td></tr>";
                var t = 0;
                while (t < json.ListContactGroupDetail[i].UserInGroupCount)
                {
                    if (json.ListContactGroupDetail[i].ListUsersInGroup[t].IsOnline == true)
                    {
                        html = html + "<tr onclick='createChatWindow(\"" + json.ListContactGroupDetail[i].ListUsersInGroup[t].UserID + "\", \"" + json.ListContactGroupDetail[i].ListUsersInGroup[t].UserName + "\")'><td class='stateImgOnline'></td><td class='chatUserNameTd'>" + json.ListContactGroupDetail[i].ListUsersInGroup[t].UserName + "</td></tr>";
                    }
                    else
                    {
                        html = html + "<tr onclick='createChatWindow(\"" + json.ListContactGroupDetail[i].ListUsersInGroup[t].UserID + "\", \"" + json.ListContactGroupDetail[i].ListUsersInGroup[t].UserName + "\")'><td class='stateImgOffline'></td><td class='chatUserNameTd'>" + json.ListContactGroupDetail[i].ListUsersInGroup[t].UserName + "</td></tr>";
                    }
                    //Offline
                    $("#chatBox" + json.ListContactGroupDetail[i].ListUsersInGroup[t].UserName.UserID + " span").html("");
                    t++;

                }
                totalUser += json.ListContactGroupDetail[i].UserInGroupCount;
                i++;

            }
            html = html + "</table>";
            $(".btnChat span").html("User (" + totalUser + ")");
        }        
    }
    else
        html = html + "<table><tr><td>Có lỗi sảy ra! Hãy kiểm tra kết nối internet!</td></tr></table>";

    $(".contentContactList").html(html);
}

function createChatWindow(withUserID, withUserName)
{
    /*Kiểm tra xem đã có cửa sổ chat hay chưa*/
    var chatbox = "#chatBox" + withUserID;
    var createWindow = false;
    if ($(chatbox).length)
    {
        createWindow = false;
        toogleChatBox(withUserID);
    }
    else
        createWindow = true;

    if (createWindow)
    {
        var html = "";
        /* Thêm tab*/
        html = html + "<div class='ChatTabBar' id='ChatTabBar" + withUserID + "' onClick='toogleChatBox(\"" + withUserID + "\")'><table><tr><td class='ChatTabImage'></td><td>" + withUserName + "</td></tr></table></div>";
        $("#chatBar").append(html);

        //
        html = "";
        html = html + "<div class = 'chatBox' id='chatBox" + withUserID + "' style='display:none'>";
        html = html + "<div class = 'titleDiv'> <a class='closeChat' title='Đóng cửa sổ chat này.' onClick='closeChatBox(\"" + withUserID + "\")'/> <a class='minimizeChat' title='Thu nhỏ cửa sổ' onClick='toogleChatBox(\"" + withUserID + "\")'/> ";
        html = html + withUserName;
        html = html + "<span></span>";
        html = html + "</div>";
        html = html + "<div class = 'contentDiv'>";
        html = html + "</div>";
        html = html + "<div class = 'inputDiv'>";
        html = html + "<textarea class='inputDivTxt' cols='30' onkeydown='javascript:SaveMessage(event,\"" + withUserID + "\");'/>";
        html = html + "</div>";
        html = html + "</div>";
        $("#ChatWrapperIn").append(html);

        //Lưu vào cookie       
        if ($.cookie("activeChats") != null)
        {
            //Kiểm tra trùng hay không. Nếu chưa thì add thêm.
            idsConvers = $.cookie('activeChats').split("*");
            var i = 0;
            var exist = false;
            for (i = 0; i < idsConvers.length; i++)
            {
                if (idsConvers[i] == withUserID)
                {
                    exist = true;
                }
            }
            if (!exist)
                if ($.cookie("activeChats") != "")
                    $.cookie("activeChats", $.cookie("activeChats") + "*" + withUserID)
                else
                    $.cookie("activeChats", withUserID)
        }
        else
            $.cookie("activeChats", withUserID);


        toogleChatBox(withUserID);        //
        refreshChatBoxPosition();         //
        $("#chatBox" + withUserID).click(function () { quitarTextoParpad(withUserID); });
        $("#ChatTabBar" + withUserID).click(function () { quitarTextoParpad(withUserID); });
    }
}

function SaveMessage(event, toUserID)
{
    if (event.keyCode == 13)
    {
        var chatbox = "#chatBox" + toUserID;
        var message = $(chatbox + " textarea").val();
        var fromUserID = $('#chatBar').attr('userID');
        if ((message == "") | (message == "\n")) { $(chatbox + " textarea").val(""); return };
        $.ajax({
            type: "POST",
            url: "/Views/Shared/InstantMessage/MessageServices.asmx/SaveMessage",
            data: '{"fromUser":"' + fromUserID + '", "toUser":"' + toUserID + '", "message":"' + message + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msj)
            {
                if (msj.d != "error")
                {
                    $(chatbox + " .contentDiv").append("<b>" + "Me" + "</b>: " + message + "<br />");
                    $(chatbox + " textarea").val("");
                    $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
                    //escribo en la cookie
                    $.cookie("chat" + toUserID, $(chatbox + " .contentDiv").html());
                }
            },
            error: function ()
            {
                $(chatbox + " .contentDiv").append("Không thể gửi tin nhắn. <br />");
            }
        });
        event.returnValue = false; //Chrome fix.
    }
}

function GetMessage(UserID)
{


    //var chatbox = "#chatBox" + toUserID + " input";
    //var message = $(chatbox).val();
    //var UserID = $('#chatBar').attr('userID');

    $.ajax({
        type: "POST",
        url: "/Views/Shared/InstantMessage/MessageServices.asmx/GetMessage",
        data: '{"toUser":"' + UserID + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msj)
        {
            if (msj.d != "error")
            {
                GetMessageError(false);
                eval('var z=' + msj.d);
                //createChatWindow(z.mensajes.);                    
                var i = 0;
                while (i < z.MessageCount)
                {
                    createChatWindow(z.ListMessages[i].CreatingUser, z.ListMessages[i].CreatingUserName);
                    var message = z.ListMessages[i].MessageContent;
                    var chatbox = "#chatBox" + z.ListMessages[i].CreatingUser;
                    $(chatbox + " .contentDiv").append("<b>" + z.ListMessages[i].CreatingUserName + "</b>: " + message + "<br />");
                    $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
                    //Báo có tn mới
                    blinkChatTabBar(z.ListMessages[i].CreatingUser);
                    //Lưu cookie
                    $.cookie("chat" + z.ListMessages[i].CreatingUser, $(chatbox + " .contentDiv").html());
                    i++;
                }
                GetMessage(UserID);
            }
            else
                action = 1;

        },
        error: function ()
        {
            GetMessageError(true);
            GetMessage(UserID);
        }
    });

}


function GetMessageError(value)
{
    if (value)
    {
        $(".contentDiv").addClass("contentDivError");
        $(".inputDivTxt").val("Kết nối tới máy chủ thất bại. Hãy kiểm tra kết nối của bạn!");
        $(".inputDivTxt").attr("disabled", true);
    }
    else
    {
        if ($(".contentDiv").hasClass("contentDivError"))
        {
            $(".contentDiv").removeClass("contentDivError");
            $(".inputDivTxt").val("");
            $(".inputDivTxt").removeAttr("disabled");
        }
    }
}





/*********************************************************************************************/
/**************************      PLUGINS    **************************************************/
/*********************************************************************************************/
/*********************************************************************************************/

//2009-03-20  Plugin SETOFFSET
(function ($)
{

    $.fn.extend({

        /**
        * Stores the original version of offset(), so that we don't lose it
        */
        _offset: $.fn.offset,

        /**
        * Set or get the specific left and top position of the matched
        * elements, relative the the browser window by calling setXY
        * @param {Object} newOffset
        */
        offset: function (newOffset)
        {
            return !newOffset ? this._offset() : this.each(function ()
            {
                var el = this;

                var hide = false;

                if ($(el).css('display') == 'none')
                {
                    hide = true;
                    $(el).show();
                };

                var style_pos = $(el).css('position');

                // default to relative
                if (style_pos == 'static')
                {
                    $(el).css('position', 'relative');
                    style_pos = 'relative';
                };

                var offset = $(el).offset();

                if (offset)
                {
                    var delta = {
                        left: parseInt($(el).css('left'), 10),
                        top: parseInt($(el).css('top'), 10)
                    };

                    // in case of 'auto'
                    if (isNaN(delta.left))
                        delta.left = (style_pos == 'relative') ? 0 : el.offsetLeft;
                    if (isNaN(delta.top))
                        delta.top = (style_pos == 'relative') ? 0 : el.offsetTop;

                    if (newOffset.left || newOffset.left === 0)
                        $(el).css('left', newOffset.left - offset.left + delta.left + 'px');

                    if (newOffset.top || newOffset.top === 0)
                        $(el).css('top', newOffset.top - offset.top + delta.top + 'px');
                };
                if (hide) $(el).hide();
            });
        }

    });

})(jQuery);

/*********************  Cookie Plugin ***************************/


jQuery.cookie = function (name, value, options)
{
    if (typeof value != 'undefined')
    { // name and value given, set cookie
        options = options || {};
        if (value === null)
        {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString))
        {
            var date;
            if (typeof options.expires == 'number')
            {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else
            {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else
    { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '')
        {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++)
            {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '='))
                {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};